package com.cloud.gatewaySpringSecurity.handler;

import com.cloud.gatewaySpringSecurity.constant.TokenConstant;
import com.cloud.gatewaySpringSecurity.pojo.Payload;
import com.cloud.gatewaySpringSecurity.pojo.TokenUser;
import com.cloud.gatewaySpringSecurity.properties.RsaKeyProperties;
import com.cloud.gatewaySpringSecurity.utils.JsonUtil;
import com.cloud.gatewaySpringSecurity.utils.JwtUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/**
 * @author zzx
 * @date 2022/09/04
 *
 * 处理token
 */
@Component
public class ParseTokenHandler implements ServerSecurityContextRepository {

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    @Value("#{'${spring.cloud.gateway.login-url}'.split(',')}")
    private String[] loginUrls;

    @Value("#{'${spring.cloud.gateway.unnecessary-url}'.split(',')}")
    private String[] unnecessaryUrls;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @SneakyThrows
    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        //请求方式
        HttpMethod method = request.getMethod();
        //路径信息
        String path = request.getPath().value();
        //判断路径是否需要被处理
        for(String url : unnecessaryUrls) {
            if(url.equals(path)) {
                return Mono.empty();
            }
        }
        for (String url : loginUrls) {
            if (url.equals(path) && HttpMethod.POST.equals(method)) {
                return Mono.empty();
            }
        }
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        //从请求头中获取token
        String token = headers.getFirst(HttpHeaders.AUTHORIZATION);
        //去除掉前缀
        token = token.replace(TokenConstant.TOKEN_PREFIX, "");
        //解析token
        Payload<TokenUser> payload = JwtUtil.getInfoFromToken(token, rsaKeyProperties.getPublicKey(), TokenUser.class);
        //获取用户信息
        TokenUser user = payload.getUserInfo();
        //将用户信息转化为json格式,好存放到请求头中
        String json = JsonUtil.toString(user);
        //将请求头设置为可修改
        headers = HttpHeaders.writableHttpHeaders(headers);
        //将用户信息存放到请求头中
        headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, URLEncoder.encode(json, "utf-8"));
        //删除请求头中的token
        headers.remove(HttpHeaders.AUTHORIZATION);
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, payload.getId());
        SecurityContext securityContext = new SecurityContextImpl(usernamePasswordAuthenticationToken);
        return Mono.just(securityContext);
    }
}
